package za.co.johanmynhardt.jsf.bean;

import java.util.Calendar;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;

import za.co.johanmynhardt.jee.entity.Post;
import za.co.johanmynhardt.jee.service.PostService;

/**
 * @author johan.mynhardt@thumbtribe.mobi
 * @version 2011.1219
 */
@ViewScoped
@ManagedBean
public class ViewPostBean {
	private String id;
	private boolean edit = false;
	private String editTitle;
	private String editContent;

	Post post;

	@EJB
	private PostService service;

	public void updatePost(ActionEvent actionEvent) {
		post.setTitle(editTitle);
		post.setContent(editContent);
		post.setDate(Calendar.getInstance().getTime());

		service.savePost(post);
		edit = false;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		Logger.getAnonymousLogger().info("ID: " + id);
		this.id = id;

		if (id != null) {
			post = service.getPostById(Long.valueOf(id));
		}
	}

	public Post getPost() {
		return post;
	}

	public void setPost(Post post) {
		this.post = post;
	}

	public boolean isEdit() {
		return edit;
	}

	public void setEdit(boolean edit) {
		this.edit = edit;
		if (edit) {
			editTitle = post.getTitle();
			editContent = post.getContent();
		}
	}

	public String getEditTitle() {
		return editTitle;
	}

	public void setEditTitle(String editTitle) {
		this.editTitle = editTitle;
	}

	public String getEditContent() {
		return editContent;
	}

	public void setEditContent(String editContent) {
		this.editContent = editContent;
	}
}
